/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.chipchip.codec;

import com.chipchip.objects.CCMessage;
import com.chipchip.objects.TAttributes;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 *
 * @author Tri
 */
public class MessageDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        try {
            if(in.readableBytes() > 0) {
                if(ctx.channel().attr(TAttributes.CONN_STATUS_KEY).get() == TAttributes.STATE_CONNECTED) {
                    System.out.println("Available: " + in.readableBytes());

                    int dataLength = Integer.valueOf(in.readInt());
                    System.out.println("DataLength: " + dataLength);
                    // Wait until the whole data is available

                    if(in.readableBytes() < dataLength) {
                        in.resetReaderIndex();
                        return;
                    }
                    // Convert the received data into a new Message. 

                    byte[] decoded = new byte[dataLength];
                    in.readBytes(decoded);
                    CCMessage msg = new CCMessage(decoded);
                    System.err.println("message decoded");  
                    out.add(msg);
                } else {
                    byte[] data = new byte[in.readableBytes()];
                    in.readBytes(data);
                    String policyRequest = new String(data);
                    System.out.println("Policy Request: \n" + policyRequest);
                    ctx.channel().attr(TAttributes.CONN_STATUS_KEY).set(TAttributes.STATE_CONNECTED);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
